<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/admin/AdminAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Department.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Employee.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/DepartmentType.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Pattern.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class DepartmentUpdateAction extends AdminAction {
	protected function execute(Response $response) {
		$department = null;
		if(isset($_POST['name']) && Str::isMatch(Pattern::WORDS, $_POST['name']) &&
				isset($_POST['type'])) {
			$department = new Department();
			$department->setName($_POST['name']);
			$type = new DepartmentType();
			$type->setIdentity($_POST['type']);
			$department->setType($type);
			if(isset($_POST['parent']) && Str::isNotEmpty($_POST['parent'])) {
				$parent = new Department();
				$parent->setIdentity($_POST['parent']);
				
				$department->setParent($parent);
			}
			if(isset($_POST['head']) && Str::isNotEmpty($_POST['head'])) {
				$employee = new Employee();
				$employee->setIdentity($_POST['head']);
				$department->setHead($employee);
			}
			$serviceFactory = new ServiceFactory();
			$service = $serviceFactory->getService('DepartmentService');
			if(isset($_POST['identity'])) {
				$department->setIdentity($_POST['identity']);
			}
			$service->save($department);
		}
		if($department !== null) {
			$_SESSION['department-identity'] = $department->getIdentity();
			$response->setActionPath('/department/edit.html');
		} else {
			$response->setActionPath('/department/index.html');
		}
	}
}
?>